package com.newlink.building.userinfo.fragment

import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ImageView
import android.widget.ListView
import android.widget.TextView
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.sdk.android.push.CommonCallback
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory
import com.newlink.building.common_base.activities.NL_WebViewActivityNL
import com.newlink.building.common_base.base.BaseMvpFragment
import com.newlink.building.common_base.constant.Base_Constant
import com.newlink.building.common_base.constant.Base_RouterPath
import com.newlink.building.common_base.event.MessageEvent
import com.newlink.building.common_base.event.ReadCountActionEvent
import com.newlink.building.common_base.event.TYPE_APP_EXIT
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.model.bean.PolicyAgreementData
import com.newlink.building.common_base.model.bean.UserInfoData
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.GarbageUtils
import com.newlink.building.common_base.utils.Base_Preference
import com.newlink.building.common_base.utils.ToastUtils
import com.newlink.building.common_base.utils.logDebug
import com.newlink.building.common_base.widget.CustomMessageDialog
import com.newlink.building.manager.Module_Phone_VoipController
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.activity.Module_UserInfo_AboutActivityNL
import com.newlink.building.userinfo.activity.Module_UserInfo_AccountInformationActivityNL
import com.newlink.building.userinfo.activity.Module_UserInfo_AuthManageActivityNL
import com.newlink.building.userinfo.activity.Module_UserInfo_CallSettingActivityNL
import com.newlink.building.userinfo.activity.Module_UserInfo_DeviceSettingActivityNL
import com.newlink.building.userinfo.activity.Module_UserInfo_FamilyManagementActivityNL
import com.newlink.building.userinfo.activity.Module_UserInfo_HelpActivityNL
import com.newlink.building.userinfo.activity.MessageCenterActivityNL
import com.newlink.building.userinfo.activity.Module_UserInfo_NotifySettingActivityNL
import com.newlink.building.userinfo.activity.Module_UserInfo_PropertyManagementActivityNL
import com.newlink.building.userinfo.adapter.Module_UserInfo_PersonalMenuAdapter
import com.newlink.building.userinfo.databinding.FragmentPersonalBinding
import com.newlink.building.userinfo.model.PersonalMenuItem
import com.newlink.building.userinfo.mvp.Module_UserInfo_PersonalPresenter
import com.newlink.building.userinfo.mvp.contract.Module_UserInfo_PersonalContract
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationHelper
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationInvoker
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.image
import java.util.Locale

/**
 * @author wangyang
 * @date 2022/9/13
 * @description 我的页面的Fragment
 */
class Module_UserInfo_PersonalFragment : BaseMvpFragment<Module_UserInfo_PersonalContract.View, Module_UserInfo_PersonalContract.Presenter>(),
    Module_UserInfo_PersonalContract.View {

    // 绑定视图实例
    private lateinit var binding: FragmentPersonalBinding

    // 本地消息数量
    private var localMessageCount: Int = 0

    // 通知消息数量
    private var noticeMessageCount: Int = 0

    // 用户账户名称TextView
    private lateinit var accountNameTextView: TextView

    // ListView和适配器
    private lateinit var menuListView: ListView
    private lateinit var menuAdapter: Module_UserInfo_PersonalMenuAdapter
    private val menuItems = mutableListOf<PersonalMenuItem>()

    // Companion object 用于提供Fragment实例
    companion object {
        private const val TAG = "PersonalFragment"

        // 菜单项ID常量
        private const val MENU_MESSAGE_CENTER = 1001
        private const val MENU_TERMS_AUTH = 1002
        private const val MENU_FAMILY_MANAGEMENT = 1003
        private const val MENU_PROPERTY_MANAGEMENT = 1004
        private const val MENU_DEVICE_SETTING = 1005
        private const val MENU_NOTIFY_SETTING = 1006
        private const val MENU_HELP_AND_FEEDBACK = 1007
        private const val MENU_TERMS_AND_POLICIES = 1008
        private const val MENU_ABOUT = 1009
        private const val MENU_CALL_SETTING = 1010

        fun getInstance(): Module_UserInfo_PersonalFragment = Module_UserInfo_PersonalFragment()
    }

    /**
     * 创建Presenter实例
     */
    override fun createPresenter(): Module_UserInfo_PersonalContract.Presenter {
        return Module_UserInfo_PersonalPresenter()
    }

    /**
     * 绑定布局文件
     */
    override fun attachLayoutRes(): View {
        binding = FragmentPersonalBinding.inflate(layoutInflater)
        return binding.root
    }

    /**
     * 初始化视图组件
     */
    override fun initView(view: View) {
        super.initView(view)
        // Fragment初始化时添加混淆
        Module_Obfuscation_ObfuscationHelper.onMethodEnter("PersonalFragment", "initView")
        Module_Obfuscation_ObfuscationInvoker.invokeRandom(view.hashCode())

        initializeListView()
        setupMenuData()
        setupClickListeners()
        initializeMessageCenterStatus()
        updateAccountInfoDisplay()
    }

    /**
     * 初始化ListView
     */
    private fun initializeListView() {
        menuListView = binding.lvPersonalMenu
        menuAdapter = Module_UserInfo_PersonalMenuAdapter(requireContext(), menuItems)
        menuListView.adapter = menuAdapter

        menuListView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
            handleMenuItemClick(menuItems[position])
        }
    }

    /**
     * 设置菜单数据
     */
    private fun setupMenuData() {
        menuItems.clear()

        // 消息中心
        menuItems.add(PersonalMenuItem(
            id = MENU_MESSAGE_CENTER,
            title = getString(R.string.message_center),
            iconResId = R.mipmap.personal_message_center,
            hasUnreadBadge = false // 将在更新时设置
        ))

        // 分隔线
        menuItems.add(PersonalMenuItem(
            id = -1,
            title = "",
            iconResId = 0,
            isGroup = true,
            hasArrow = false
        ))

        // 授权管理
        menuItems.add(PersonalMenuItem(
            id = MENU_TERMS_AUTH,
            title = getString(R.string.authorization_management),
            iconResId = R.mipmap.personal_terms_and_policies
        ))

        // 家庭管理 (根据用户类型显示)
        if (shouldShowFamilyManagement()) {
            menuItems.add(PersonalMenuItem(
                id = MENU_FAMILY_MANAGEMENT,
                title = getString(R.string.family_management),
                iconResId = R.mipmap.personal_family_management
            ))
        }

        // 物业管理 (根据用户类型显示)
        if (shouldShowPropertyManagement()) {
            menuItems.add(PersonalMenuItem(
                id = MENU_PROPERTY_MANAGEMENT,
                title = getString(R.string.property_management),
                iconResId = R.mipmap.personal_property_management
            ))
        }

        // 设备管理 (根据用户类别显示)
        if (shouldShowDeviceManagement()) {
            // 分隔线
            menuItems.add(PersonalMenuItem(
                id = -2,
                title = "",
                iconResId = 0,
                isGroup = true,
                hasArrow = false
            ))

            menuItems.add(PersonalMenuItem(
                id = MENU_DEVICE_SETTING,
                title = getString(R.string.device_setting),
                iconResId = R.mipmap.personal_device_management
            ))
        }

        // 通知设置
        menuItems.add(PersonalMenuItem(
            id = MENU_NOTIFY_SETTING,
            title = getString(R.string.notify_setting),
            iconResId = R.mipmap.ic_notify_setting
        ))

        // 分隔线
        menuItems.add(PersonalMenuItem(
            id = -3,
            title = "",
            iconResId = 0,
            isGroup = true,
            hasArrow = false
        ))

        // 帮助与反馈
        menuItems.add(PersonalMenuItem(
            id = MENU_HELP_AND_FEEDBACK,
            title = getString(R.string.help_and_feedback),
            iconResId = R.mipmap.personal_help_and_feedback
        ))

        // 用户协议
        menuItems.add(PersonalMenuItem(
            id = MENU_TERMS_AND_POLICIES,
            title = getString(R.string.user_register_license_privacy),
            iconResId = R.mipmap.personal_terms_and_policies2
        ))

        // 关于
        menuItems.add(PersonalMenuItem(
            id = MENU_ABOUT,
            title = getString(R.string.about),
            iconResId = R.mipmap.personal_about
        ))

        menuAdapter.notifyDataSetChanged()
    }

    /**
     * 处理菜单项点击
     */
    private fun handleMenuItemClick(item: PersonalMenuItem) {
        if (item.isGroup) return

        // 点击事件处理前的混淆
        Module_Obfuscation_ObfuscationInvoker.invokeSpecific(12, item.id)
        Module_Obfuscation_ObfuscationHelper.beforeDatabaseOperation("onClick", item.id)

        when (item.id) {
            MENU_MESSAGE_CENTER -> navigateToMessageCenter()
            MENU_TERMS_AUTH -> navigateToAuthManagement()
            MENU_FAMILY_MANAGEMENT -> navigateToFamilyManagement()
            MENU_PROPERTY_MANAGEMENT -> navigateToPropertyManagement()
            MENU_CALL_SETTING -> navigateToCallSetting()
            MENU_NOTIFY_SETTING -> navigateToNotificationSetting()
            MENU_HELP_AND_FEEDBACK -> requestFAQInfo()
            MENU_TERMS_AND_POLICIES -> requestAgreementInfo()
            MENU_ABOUT -> navigateToAboutPage()
            MENU_DEVICE_SETTING -> navigateToDeviceManagement()
        }
    }

    /**
     * 判断是否显示家庭管理
     */
    private fun shouldShowFamilyManagement(): Boolean {
        return try {
            userInfoData.prjType != 3 && userInfoData.userCategory != 3
        } catch (e: Exception) {
            true // 默认显示
        }
    }

    /**
     * 判断是否显示物业管理
     */
    private fun shouldShowPropertyManagement(): Boolean {
        return try {
            !(userInfoData.userCategory == 2 || userInfoData.userCategory == 3 || userInfoData.prjType == 1)
        } catch (e: Exception) {
            true // 默认显示
        }
    }

    /**
     * 判断是否显示设备管理
     */
    private fun shouldShowDeviceManagement(): Boolean {
        return try {
            userInfoData.userCategory == 2
        } catch (e: Exception) {
            false // 默认不显示
        }
    }

    /**
     * 设置点击监听器（现在只需要头部和退出按钮）
     */
    private fun setupClickListeners() {
        binding.headContainer.root.setOnClickListener { navigateToAccountInfo() }
        binding.btnLogout.setOnClickListener { handleLogoutAttempt() }
    }

    /**
     * 初始化消息中心未读状态显示
     */
    private fun initializeMessageCenterStatus() {
        accountNameTextView = view?.findViewById(R.id.tv_account_name) ?: TextView(context)
        // 未读状态现在通过ListView适配器管理
    }

    /**
     * 更新账户信息显示
     */
    private fun updateAccountInfoDisplay() {
        activity?.findViewById<TextView>(R.id.tv_account_number)?.text = "$agoraId"
    }

    /**
     * Fragment可见时加载数据
     */
    override fun onResume() {
        super.onResume()
        logDebug<Module_UserInfo_PersonalFragment>("[jake]..personalFragment.onResume...........")
        mPresenter?.getUserInfo(accessToken, userId)
    }

    /**
     * 懒加载方法，当前未实现具体逻辑
     */
    override fun lazyLoad() {
        // 当前未实现具体懒加载逻辑
    }


    /**
     * 导航到账户信息页面
     */
    private fun navigateToAccountInfo() {
        startActivity(Intent(activity, Module_UserInfo_AccountInformationActivityNL::class.java))
    }

    /**
     * 导航到消息中心页面
     */
    private fun navigateToMessageCenter() {
        Intent(activity, MessageCenterActivityNL::class.java).apply {
            putExtra(Base_Constant.KEY_MESSAGE_COUNT, localMessageCount)
            putExtra(Base_Constant.KEY_NOTICE_COUNT, noticeMessageCount)
            startActivity(this)
        }
    }

    /**
     * 导航到授权管理页面
     */
    private fun navigateToAuthManagement() {
        startActivity(Intent(activity, Module_UserInfo_AuthManageActivityNL::class.java))
    }

    /**
     * 导航到家庭管理页面
     */
    private fun navigateToFamilyManagement() {
        startActivity(Intent(activity, Module_UserInfo_FamilyManagementActivityNL::class.java))
    }

    /**
     * 导航到物业管理页面
     */
    private fun navigateToPropertyManagement() {
        startActivity(Intent(activity, Module_UserInfo_PropertyManagementActivityNL::class.java))
    }

    /**
     * 导航到通话设置页面
     */
    private fun navigateToCallSetting() {
        startActivity(Intent(activity, Module_UserInfo_CallSettingActivityNL::class.java))
    }

    /**
     * 导航到通知设置页面
     */
    private fun navigateToNotificationSetting() {
        logDebug<Module_UserInfo_PersonalFragment>("rl_notify_setting")
        startActivity(Intent(activity, Module_UserInfo_NotifySettingActivityNL::class.java))
    }

    /**
     * 请求常见问题解答信息
     */
    private fun requestFAQInfo() {
        mPresenter?.getFAQ()
    }

    /**
     * 请求用户协议信息
     */
    private fun requestAgreementInfo() {
        mPresenter?.getAgreement()
    }

    /**
     * 导航到关于页面
     */
    private fun navigateToAboutPage() {
        startActivity(Intent(activity, Module_UserInfo_AboutActivityNL::class.java))
    }

    /**
     * 处理登出尝试
     */
    private fun handleLogoutAttempt() {
        if (isCurrentlyCalling()) {
            ToastUtils.showTextToast(
                requireContext(),
                resources.getString(R.string.calling_cannot_exit)
            )
            return
        }
        showLogoutConfirmationDialog()
    }

    /**
     * 检查当前是否处于通话状态
     */
    private fun isCurrentlyCalling(): Boolean {
        // 原始代码注释掉了CallManager的调用，因此此处保持返回false
        // if (CallManager.get().isCallingState()) { return true }
        return false
    }

    /**
     * 显示登出确认对话框
     */
    private fun showLogoutConfirmationDialog() {
        CustomMessageDialog(requireContext()).apply {
            setTitle(resources.getString(R.string.logout))
            setMessage(resources.getString(R.string.dialog_default_exit_account))
            setPositiveButton(resources.getString(R.string.confirm_dialog_custom), object :
                CustomMessageDialog.OnClickListener {
                override fun onClick(dialog: CustomMessageDialog) {
                    mPresenter?.logout(accessToken)
                    dialog.dismiss()
                }
            })
            setNegativeButton(
                resources.getString(R.string.cancel_dialog_custom),
                object : CustomMessageDialog.OnClickListener {
                    override fun onClick(dialog: CustomMessageDialog) {
                        dialog.dismiss()
                    }
                })
        }.show()
    }

    /**
     * 导航到设备管理页面
     */
    private fun navigateToDeviceManagement() {
        startActivity(Intent(activity, Module_UserInfo_DeviceSettingActivityNL::class.java))
    }

    /**
     * 获取未读标记成功回调
     */
    override fun getUnreadFlagSuccess(hasUnread: Boolean?, msgCount: Int, noticeCount: Int) {
        NLog.e("[jake] ... FLS unread $hasUnread")
        localMessageCount = msgCount
        noticeMessageCount = noticeCount

        updateMessageCenterBadge(hasUnread ?: false)
    }

    /**
     * 获取通知未读标记成功回调
     */
    override fun getNoticeUnreadFlagSuccess(hasUnread: Boolean?) {
        updateMessageCenterBadge(hasUnread ?: false)
    }

    /**
     * 获取本地未读标记成功回调
     */
    override fun getLocalUnreadSuccess(hasUnread: Boolean?) {
        NLog.e("[jake] ... Local unread $hasUnread")
        updateMessageCenterBadge(hasUnread ?: false)
    }

    /**
     * 更新消息中心的未读标记
     */
    private fun updateMessageCenterBadge(hasUnread: Boolean) {
        val messageCenterIndex = menuItems.indexOfFirst { it.id == MENU_MESSAGE_CENTER }
        if (messageCenterIndex != -1) {
            menuItems[messageCenterIndex] = menuItems[messageCenterIndex].copy(hasUnreadBadge = hasUnread)
            menuAdapter.notifyDataSetChanged()
        }
    }

    /**
     * 获取用户信息成功回调
     */
    override fun getUserInfoSuccess(userInfo: UserInfoData) {
        logDebug<Module_UserInfo_PersonalFragment>("getUserInfoSuccess new:${userInfo.name} old:${userInfoResp.name}")
        userInfoData = userInfo
        updateUserInfoDisplay(userInfo)
        // 用户信息更新后重新构建菜单，以反映权限变化
        setupMenuData()
    }

    /**
     * 更新用户信息显示
     */
    private fun updateUserInfoDisplay(userInfo: UserInfoData) {
        val headImageView = activity?.findViewById<ImageView>(R.id.iv_account_head)
        headImageView?.setImageResource(R.mipmap.personal_head)
        accountNameTextView.text = userInfo.name
    }

    /**
     * 登出成功回调
     */
    override fun logoutSuccess() {
        showToast(getString(R.string.logout_success))

        Module_Phone_VoipController.get().delete()
        isLogin = false
        turnOffPushAndUnbindAccount()
        clearLocalPreferences()

        EventBus.getDefault().post(MessageEvent(TYPE_APP_EXIT, true))
        ARouter.getInstance().build(Base_RouterPath.PATH_LOGIN).navigation()
        activity?.finish()
    }

    /**
     * 关闭推送通道并解绑账户
     */
    private fun turnOffPushAndUnbindAccount() {
        val pushService = PushServiceFactory.getCloudPushService()
        pushService.turnOffPushChannel(object : CommonCallback {
            override fun onSuccess(p0: String?) {
                NLog.e("[PushService] >>>> turnOffPushChannel onSuccess >> $p0")
            }

            override fun onFailed(p0: String?, p1: String?) {
                NLog.e("[PushService] >>>> turnOffPushChannel onFailed >> $p0")
            }
        })
        pushService.unbindAccount(null)
    }

    /**
     * 清除本地偏好设置
     */
    private fun clearLocalPreferences() {
        Base_Preference.clearPreference(Base_Constant.USER_INFO_KEY)
        Base_Preference.clearPreference(Base_Constant.MQTT_INFO_KEY)
        Base_Preference.clearPreference(Base_Constant.USER_INFO_RESP_KEY)
        Base_Preference.clearPreference(Base_Constant.COUNTRY_DEFAULT)
        Base_Preference.clearPreference(Base_Constant.COUNTRY_LIST)
        Base_Preference.clearPreference(Base_Constant.PRJ_ID_KEY)
        Base_Preference.clearPreference(Base_Constant.PRJ_DATA_KEY)
    }

    /**
     * 请求失败回调
     */
    override fun onFail() {
        val headImageView = activity?.findViewById<ImageView>(R.id.iv_account_head)
        headImageView?.image = context?.getDrawable(R.mipmap.personal_head)
        activity?.findViewById<TextView>(R.id.tv_account_name)?.text = ""
        activity?.findViewById<TextView>(R.id.tv_account_number)?.text = ""
        updateMessageCenterBadge(false)
    }

    /**
     * 获取协议成功回调
     */
    override fun onGetAgreementSuccess(data: PolicyAgreementData?) {
        data?.policyPath?.let {
            NL_WebViewActivityNL.startSelf(
                activity,
                it,
                resources.getString(R.string.user_register_license_privacy)
            )
        }
    }

    /**
     * 获取常见问题解答URL成功回调
     */
    override fun onGetFAQSuccess(url: String?) {
        if (!url.isNullOrEmpty()) {
            startActivity(Intent(activity, Module_UserInfo_HelpActivityNL::class.java).apply {
                putExtra("link", url)
            })
        }
    }

    /**
     * 处理读取计数事件的订阅方法
     * 当收到ReadCountActionEvent时更新消息中心未读状态
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReadCountActionEvent(event: ReadCountActionEvent) {
        if (event.type == 1 && event.index == 1) {
            updateMessageCenterBadge(true)
        }
    }

    /**
     * Fragment可见时调用，刷新未读消息状态
     */
    override fun onVisible() {
        super.onVisible()
        // 获取FLS的未读消息
        mPresenter?.getUnreadFlag(accessToken, 1)
    }

    private fun processMyData(originalData: String): String {
        Log.i(TAG, "Starting processMyData with original data: $originalData")

        val processedGarbageData = GarbageUtils.processGarbage(originalData)

        val finalResult = "FinalProcessed_" + processedGarbageData.uppercase(Locale.getDefault())

        Log.i(TAG, "Finished processMyData. Final result: $finalResult")
        return finalResult
    }
}